package com.ebupt.migu.music.hangupsms.controller;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ebupt.migu.common.util.RestHttpUtil;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.util.EmptyUtils;
import com.ebupt.migu.music.common.util.RedisUtil;
import com.ebupt.migu.music.hangupsms.entity.BillInfo;
import com.ebupt.migu.music.hangupsms.entity.IssueInfo;
import com.ebupt.migu.music.hangupsms.entity.IssueInfoPage;
import com.ebupt.migu.music.hangupsms.entity.VrbtSendMsg;
import com.ebupt.migu.music.hangupsms.service.IIssueInfoService;
import com.ebupt.migu.music.hangupsms.utils.DidUtils;
import com.ebupt.migu.music.hangupsms.utils.LocalDateTimeUtils;
import com.ebupt.migu.music.market.entity.MarketSmsStrategy;
import com.ebupt.migu.music.market.service.MarketSmsStrategyService;
import lombok.extern.slf4j.Slf4j;


import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/issueInfo")
@Slf4j
public class IssueInfoController {
	@Autowired
	private IIssueInfoService issueInfoService;
	@Value("${music.phoneUrl}")
	private String phoneUrl;
	@Value("${music.ringUrl}")
	private String ringUrl;
	@Value("${music.did}")
	private String did;
	@Value("${music.pwd}")
	private String pwd;
	@Value("${music.platform}")
	private String platform;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private MarketSmsStrategyService marketSmsStrategyService;
	@GetMapping(value = "/list")
	public ResultObject<IPage<IssueInfo>> queryPageList(IssueInfoPage issueInfo,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		QueryWrapper<IssueInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda()
				.eq(!EmptyUtils.isEmpty(issueInfo.getPhoneNumber()), IssueInfo::getPhoneNumber, issueInfo.getPhoneNumber())
				.eq(!EmptyUtils.isEmpty(issueInfo.getProvinceCode())&&!Arrays.asList(issueInfo.getProvinceCode().split(",")).contains("00"), IssueInfo::getProvinceCode, issueInfo.getProvinceCode())
				.eq(!EmptyUtils.isEmpty(issueInfo.getSmsId()), IssueInfo::getSmsId, issueInfo.getSmsId())
				.eq(!EmptyUtils.isEmpty(issueInfo.getDeliverTime()), IssueInfo::getDeliverTime, issueInfo.getDeliverTime())
				.between(!EmptyUtils.isEmpty(issueInfo.getStartTime()) && !EmptyUtils.isEmpty(issueInfo.getEndTime()), IssueInfo::getDeliverTime, issueInfo.getStartTime(), issueInfo.getEndTime())
				.orderByDesc(IssueInfo::getCreateTime);
		Page<IssueInfo> page = new Page<IssueInfo>(pageNo, pageSize);
		IPage<IssueInfo> pageList = issueInfoService.page(page, queryWrapper);
		return ResultObject.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param issueInfo
	 * @return
	 */
	@PostMapping(value = "/add")
	public ResultObject<String> add(@RequestBody IssueInfo issueInfo) {
		issueInfoService.save(issueInfo);
		return ResultObject.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param issueInfo
	 * @return
	 */
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public ResultObject<String> edit(@RequestBody IssueInfo issueInfo) {
		issueInfoService.updateById(issueInfo);
		return ResultObject.ok("编辑成功!");
	}
	@KafkaListener(topics = "huadan-spcl-filter-by-person",groupId = "RFMENT-huadan-spcl-filter-by-person")
	@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
	public void offline1130(ConsumerRecord<?, ?> record)  {
		Optional<?> kafkaMessage = Optional.ofNullable(record.value());
		if (kafkaMessage.isPresent()) {
			String content = (String) kafkaMessage.get();
			log.info("挂机短信收到消息：{}", content);
			BillInfo billInfo = issueInfoService.getBillInfo(content);
			// 查询是否是移动号段
			String CallerProvince = issueInfoService.isMobile(billInfo.getCallerPhone());
			if(StringUtils.isEmpty(CallerProvince)){
				log.info("不是移动号段，不发送短信");
				return;
			}
			billInfo.setCallerProvinceId(CallerProvince);
			List<MarketSmsStrategy> strategies = issueInfoService.queryStrategy(billInfo);
			if (CollectionUtils.isEmpty(strategies)) {
				log.info("没有相关策略");
				return;
			}
			for(MarketSmsStrategy smsStrategy:strategies){
				billInfo.setSmsStrategy(smsStrategy);
				if (issueInfoService.contentPreProcess(billInfo)) {
					issueInfoService.contentProcess(billInfo);
				}
			}

		}
	}
	@RequestMapping("/test")
	public void test(String content){
		Integer o = (Integer)redisUtil.get("33333");
		log.info("挂机短信收到消息：{}", content);
		BillInfo billInfo = issueInfoService.getBillInfo(content);
		// 查询是否是移动号段
//		String CallerProvince = issueInfoService.isMobile(billInfo.getCallerPhone());
//		if(StringUtils.isEmpty(CallerProvince)){
//			log.info("不是移动号段，不发送短信");
//			return;
//		}
		billInfo.setCallerProvinceId("11");
		Date date1 = DateUtil.parse(billInfo.getStartTime(), "yyyyMMddHHmmss");
		Date date2 = DateUtil.parse(billInfo.getEndTime(), "yyyyMMddHHmmss");
		// 计算两个日期之间相差的秒数
		long diffSeconds = DateUtil.between(date1, date2, DateUnit.SECOND);
		billInfo.setDuration(diffSeconds);		// 主叫|被叫|plus铃音编号|铃音id|开始时间|结束时间
		// 13801396200|13911912008||600926000001209039|20201217092552|20201217092600
		// 新增省份字段：beijing|13801396200|13911912008||600926000001209039|20201217092552|20201217092600
		billInfo.setUserType("10");
		List<MarketSmsStrategy> strategies = issueInfoService.queryStrategy(billInfo);
		//todo 1.先调接口判断是否是普通用户2.获取挂机短信策略，如果没有则去宣发平台查询 都没有就不下发
		if (CollectionUtils.isEmpty(strategies)) {
			log.info("没有相关策略");
			return;
		}
		for(MarketSmsStrategy smsStrategy:strategies){
			billInfo.setSmsStrategy(smsStrategy);
			if (issueInfoService.contentPreProcess(billInfo)) {
				issueInfoService.contentProcess(billInfo);
			}
		}
	}
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public ResultObject<String> delete(@RequestParam(name="id",required=true) String id) {
		issueInfoService.removeById(id);
		return ResultObject.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public ResultObject<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.issueInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return ResultObject.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public ResultObject<IssueInfo> queryById(@RequestParam(name="id",required=true) String id) {
		IssueInfo issueInfo = issueInfoService.getById(id);
		if(issueInfo==null) {
			return ResultObject.error("未找到对应数据");
		}
		return ResultObject.ok(issueInfo);
	}
	@PostMapping(value = "/ttt")
	public Map ttt(HttpServletRequest request) {
		HashMap map1 = new HashMap();
		HashMap map2 = new HashMap();
		map2.put("resultCode","000001");
		map2.put("resultMessage","服务器繁忙");
		map1.put("result",map2);
		map1.put("isHasRights",0);
		return map1;
	}
	@GetMapping(value = "/ttt1")
	public Map ttt1(HttpServletRequest request) {
		HashMap map1 = new HashMap();

		map1.put("resultCode","000000");
		map1.put("resultMessage","服务器繁忙");
//		map1.put("data",21);


		DateTime nowTime = DateUtil.parse(new SimpleDateFormat("HH:mm:ss").format(new Date()), "HH:mm:ss");

		if (!timeCalendar(nowTime, cn.hutool.core.date.DateUtil.parse("09:10:12", "HH:mm:ss"),
				DateUtil.parse("16:10:12", "HH:mm:ss"))) {
			log.info("不在里面");
		}
		return map1;
	}

	public static boolean timeCalendar(Date nowTime, Date dayTimeStart, Date dayTimeEnd) {
		// 设置当前时间
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
		// 设置开始时间
		Calendar timeStart = Calendar.getInstance();
		timeStart.setTime(dayTimeStart);
		// 设置结束时间
		Calendar timeEnd = Calendar.getInstance();
		timeEnd.setTime(dayTimeEnd);
		return date.after(timeStart) && date.before(timeEnd);
	}



}
